define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'user/user/index',
                    add_url: 'user/user/add',
                    edit_url: 'user/user/edit',
                    multi_url: 'user/user/multi',
                    del_url: 'user/user/del',
                    table: 'fa_user',
                }
            });

            // 自定义状态格式化函数
            var customStatusFormatter = function (value, row, index) {
                var statusMap = {
                    "0": __('已禁用'),
                    "normal": __('正常'),
                    "2": __('已锁定'),
                    "3": __('待审核')
                };
                var nextStatus = value === 'normal' ? '0' : 'normal';
                var icon = value === 'normal' ? 'fa-toggle-on text-success' : 'fa-toggle-off text-gray';
                return '<a href="javascript:;" class="btn-change-status" data-id="' + row.id + '" data-status="' + nextStatus + '">' +
                    '<i class="fa ' + icon + ' fa-2x"></i> ' +
                    statusMap[value] +
                    '</a>';
            };

            $(document).on('click', '.btn-change-status', function () {
                var id = $(this).data('id');
                var url ='/user/user/changeStatus?XDEBUG_SESSION_START=5432543';
                var status = $(this).data('status');
                $.post(url, {id: id, status: status}, function(response) {
                    if (response.code === 1) {
                        $([tableAll, tableStudents, tableTeachers, tableAdmins]).each(function() {
                            $(this).bootstrapTable('refresh');
                        });
                    } else {
                        Layer.alert(response.msg);
                    }
                }, 'json').fail(function() {
                    Layer.alert('网络错误，请稍后重试');
                });
            });
            $(document).ready(function() {
                // 遍历每个 .tab-pane
                $('.tab-pane').each(function() {
                    // 找到当前 .tab-pane 中的 .toolbar2
                    var toolbar = $(this).find('.toolbar2');
                    // 找到当前 .tab-pane 中的 .bs-bars.pull-left
                    var bsBars = $(this).find('.bs-bars.pull-left');
                    // 将 .toolbar2 移动到 .bs-bars.pull-left 中
                    toolbar.appendTo(bsBars);
                });
            });

            // 初始化所有用户表格
            var table = $("#tableAll");
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'weigh,id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'group_id', title: '组别ID'},
                        {field: 'username', title: '姓名'},
                        {field: 'mobile', title: '手机号'},
                        {field: 'avatar', title: '头像', formatter: Table.api.formatter.image},
                        {field: 'liveaddr', title: '居住地'},
                        {field: 'jointime', title: '加入时间', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: '状态', formatter: customStatusFormatter , searchList: {"0": __('已禁用'), "normal": __('正常'), "2": __('已锁定'), "3": __('待审核')}},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: []
                        }
                    ]
                ]
            });

            // 初始化学生表格
            var tableStudents = $("#tableStudents");
            tableStudents.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    params.group_id = 1; // 学生组ID
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'id',
                extend: {
                    add_url: 'user/user/add?group_id=1',
                    edit_url: 'user/user/edit?group_id=1',
                    del_url: 'user/user/del?group_id=1',
                    multi_url: 'user/user/multi?group_id=1',
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'group_id', title: '组别ID'},
                        {field: 'username', title: '姓名'},
                        {field: 'mobile', title: '手机号'},
                        {field: 'avatar', title: '头像', formatter: Table.api.formatter.image},
                        {field: 'liveaddr', title: '居住地'},
                        {field: 'jointime', title: '加入时间', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: '状态', formatter: customStatusFormatter, searchList: {"0": __('已禁用'), "normal": __('正常'), "2": __('已锁定'), "3": __('待审核')}},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: []
                        }
                    ]
                ]
            });

            // 初始化教师表格
            var tableTeachers = $("#tableTeachers");
            tableTeachers.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    params.group_id = 2; // 教师组ID
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'weigh,id',
                extend: {
                    add_url: 'user/user/add?group_id=2',
                    edit_url: 'user/user/edit?group_id=2',
                    del_url: 'user/user/del?group_id=2',
                    multi_url: 'user/user/multi?group_id=2',
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'group_id', title: '组别ID'},
                        {field: 'username', title: '姓名'},
                        {field: 'mobile', title: '手机号'},
                        {field: 'avatar', title: '头像', formatter: Table.api.formatter.image},
                        {field: 'liveaddr', title: '居住地'},
                        {field: 'jointime', title: '加入时间', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: '状态', formatter: customStatusFormatter, searchList: {"0": __('已禁用'), "normal": __('正常'), "2": __('已锁定'), "3": __('待审核')}},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: []
                        }
                    ]
                ]
            });

            // 初始化管理员表格
            var tableAdmins = $("#tableAdmins");
            tableAdmins.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    params.group_id = 3; // 管理员组ID
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'weigh,id',
                extend: {
                    add_url: 'user/user/add?group_id=3',
                    edit_url: 'user/user/edit?group_id=3',
                    del_url: 'user/user/del?group_id=3',
                    multi_url: 'user/user/multi?group_id=3',
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'group_id', title: '组别ID'},
                        {field: 'username', title: '姓名'},
                        {field: 'mobile', title: '手机号'},
                        {field: 'avatar', title: '头像', formatter: Table.api.formatter.image},
                        {field: 'liveaddr', title: '居住地'},
                        {field: 'jointime', title: '加入时间', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: '状态', formatter: customStatusFormatter, searchList: {"0": __('已禁用'), "normal": __('正常'), "2": __('已锁定'), "3": __('待审核')}},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: []
                        }
                    ]
                ]
            });

            $(document).on('fa.event.success', function(event, data) {
                setTimeout(function() {
                    location.reload();
                }, 1000);
            });

            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);

            // 为表格绑定事件
            Table.api.bindevent(tableStudents);
            Table.api.bindevent(tableTeachers);
            Table.api.bindevent(tableAdmins);
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
        },
        edit: function () {
            var row = JSON.parse($('#row').val());
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    return '<a class="btn-change btn-switcher ' + (value === 'normal' ? 'active' : '') + '" data-id="' + row.id + '" data-url="user/user/status" data-params="status=' + (value === 'normal' ? '0' : 'normal') + '"><i class="fa ' + (value === 'normal' ? 'fa-toggle-on' : 'fa-toggle-off text-gray') + ' fa-2x"></i></a>';
                }
            },
            events: {
                ip: {
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        }
    };
    return Controller;
});